from Common.Base import Base, open_browser

login_url = 'http://172.16.11.209:8080/ecshop/search.php?encode=YTozOntzOjg6ImtleXdvcmRzIjtzOjA6IiI7czoxMDoiaW1hZ2VGaWVsZCI7czo2OiLmkJzntKIiO3M6MTg6InNlYXJjaF9lbmNvZGVfdGltZSI7aToxNjM0MDA2MDc2O30='


class BrowseProductsPage(Base):
    """封装表现层"""
    goods_loc = ('css selector', '.goodsItem>a>img')
    next_page_loc = ('class name', 'next')

    """封装操作层: 针对表现层中元素的操作"""

    # web页面,如果发送变化,需要对元素重新定位
    def click_next_page(self):
        """
        下一页
        @return:
        """
        self.click(self.next_page_loc)

    # 1.定位页面中所有的商品.获取商品标题
    def get_goods_alts(self):
        goods = self.find_elements(self.goods_loc)  # 定位所有商品元素
        return [i.get_attribute('alt') for i in goods]

    # 2.执行浏览商品操作时,利用标题,重新定位
    def browser_product(self):
        alts = self.get_goods_alts()
        for i in alts:
            new_goods_loc = ('css selector', f'[alt*="{i}"]')  # 生成img新定位器
            self.click(new_goods_loc)
            self.back_page()


if __name__ == '__main__':
    driver = BrowseProductsPage(open_browser())
    driver.open_url(login_url)
    driver.browser_product()
    driver.click_next_page()
    driver.browser_product()
    driver.click_next_page()
    driver.browser_product()
    driver.click_next_page()
    driver.browser_product()
    driver.click_next_page()
    driver.close_browser()
